﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Spark.Config.SDK;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WebApiClient;

namespace Spark.ServiceDiscovery.Remote
{
    public class RemoteClient : IRemoteClient
    {
        private readonly ILogger<RemoteClient> _logger;
        private readonly IConfigApi _client;
        private readonly RemoteServiceDiscoveryConfiguration _serviceDiscoveryConfiguration;
        public List<Service> Services { get; set; } = new List<Service>();

        public RemoteClient(ILogger<RemoteClient> logger, RemoteServiceDiscoveryConfiguration serviceDiscoveryConfiguration)
        {
            _logger = logger;
            _serviceDiscoveryConfiguration = serviceDiscoveryConfiguration;
            //_client = HttpApiClient.Create<IConfigApi>($"http://{ _serviceDiscoveryConfiguration.Address }:{ _serviceDiscoveryConfiguration.Port}");
            _client = HttpApi.Create<IConfigApi>($"http://{ _serviceDiscoveryConfiguration.Address }:{ _serviceDiscoveryConfiguration.Port}");
            GetServices();

            Task.Run(() => Polling());
        }

        private async void Polling()
        {
            while (true)
            {
                await Task.Delay(_serviceDiscoveryConfiguration.PollingInterval);

                GetServices();
            }
        }

        private void GetServices()
        {
            try
            {
                var response = _client.GetLatestServices(_serviceDiscoveryConfiguration.AppCode).GetAwaiter().GetResult();

                if (!response.IsSuccess)
                {
                    if (_logger.IsEnabled(LogLevel.Debug))
                    {
                        _logger.LogDebug($"获取服务列表失败！【{response.Message}】");
                    }
                }
                else
                {
                    Services = response.Data;

                    if (_logger.IsEnabled(LogLevel.Debug))
                    {
                        _logger.LogDebug(JsonConvert.SerializeObject(Services));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取可用服务列表失败！");
            }
        }
    }
}